﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YJKRevitBase.WinForm;
using YJKRevitView;

namespace YJKRevitAxisModule
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdGridPartNum : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			this.m_cmdData = cmdData;
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_selection = cmdData.Application.ActiveUIDocument.Selection;
			RevitVersionFuncs.ClearSelection(this.m_selection);
			CmdViewType types = (CmdViewType)111;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (CmdGridPartNum._hWndRevit == null)
			{
                CmdGridPartNum._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			DlgGridPartNum dlgGridPartNum = new DlgGridPartNum(cmdData);
			dlgGridPartNum.Show(CmdGridPartNum._hWndRevit);
			int wMsg = 7;
			CmdGridPartNum.SendMessage(CmdGridPartNum._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			Transaction transaction = null;
			try
			{
				for (;;)
				{
					transaction = new Transaction(this.m_doc);
					transaction.Start("partnum");
					bool flag = this.AddPartNum(dlgGridPartNum);
					cmdData.Application.ActiveUIDocument.Document.Regenerate();
					if (!flag)
					{
						break;
					}
					transaction.Commit();
				}
				transaction.RollBack();
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				dlgGridPartNum.Close();
				return Autodesk.Revit.UI.Result.Failed;
			}
			dlgGridPartNum.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public bool AddPartNum(DlgGridPartNum dlg)
		{
			try
			{
				if (!dlg.IsValidatingOfNumber())
				{
					return false;
				}
				List<ElementId> list = new FilteredElementCollector(this.m_doc).OfCategory(BuiltInCategory.OST_GridChains).OfClass(typeof(MultiSegmentGrid)).ToElementIds().ToList<ElementId>();
				AxisFilter axisFilter = new AxisFilter();
				IEnumerable<Element> enumerable = this.m_selection.PickElementsByRectangle(axisFilter, "请框选轴网");
				new List<Element>();
				List<string> allGridLables = this.GetAllGridLables(this.m_cmdData);
				bool flag = false;
				foreach (Element element in enumerable)
				{
					MultiSegmentGrid multiSegmentGrid = element as MultiSegmentGrid;
					if (multiSegmentGrid != null)
					{
						string text = multiSegmentGrid.Name;
						if (!this.IsEqualsContainsPrefix(text, dlg.PartNum))
						{
							text = this.GetNameAfterSeparator(text);
							string text2 = dlg.PartNum + text;
							if (!allGridLables.Contains(text2))
							{
								multiSegmentGrid.Name = text2;
							}
							else
							{
								flag = true;
							}
						}
					}
					else
					{
						bool flag2 = false;
						foreach (ElementId elementId in list)
						{
							if ((this.m_doc.GetElement(elementId) as MultiSegmentGrid).GetGridIds().Contains(element.Id))
							{
								flag2 = true;
							}
						}
						if (!flag2)
						{
							Grid grid = element as Grid;
							if (grid != null)
							{
								string text3 = grid.Name;
								if (!this.IsEqualsContainsPrefix(text3, dlg.PartNum))
								{
									text3 = this.GetNameAfterSeparator(text3);
									string text4 = dlg.PartNum + text3;
									if (!allGridLables.Contains(text4))
									{
										grid.Name = text4;
									}
									else
									{
										flag = true;
									}
								}
							}
						}
					}
				}
				if (flag)
				{
					TaskDialog.Show("盈建科", "新轴号跟当前文档轴号有重复。");
				}
			}
			catch (Exception)
			{
				return false;
			}
			return true;
		}

		private string GetNameAfterSeparator(string name)
		{
			return AxisNameManager.GetRealLable(name);
		}

		private bool IsEqualsContainsPrefix(string name, string newContainsPrefix)
		{
			return AxisNameManager.GetContainsPrefix(name).CompareTo(newContainsPrefix) == 0;
		}

		private List<string> GetAllGridLables(ExternalCommandData cmdData)
		{
			List<string> list = new List<string>();
			foreach (Element element in AxisAssistFunc.GetAllAxis(cmdData.Application))
			{
				list.Add(element.Name);
			}
			return list;
		}

        public static WindowHandle _hWndRevit;

		private ExternalCommandData m_cmdData;

		private Document m_doc;

		private Selection m_selection;
	}
}
